package czy.demo.common.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.util.Date;

/**
 * spring mvc当中有两种拦截器
 * 一种为HandlerInterceptor,处理HttpServletRequest,HttpServletResponse,可以完结请求
 * 一种为WebRequestInterceptor,处理WebRequest,不能完结请求
 */
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {

    private DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.DEFAULT);

    /**
     * 预处理方法可以结束请求,只需要返回false即可
     * 默认情况下,返回false,请求体为空
     * 可以返回一个错误,结果为:
     * {
     *     "timestamp": "2018-07-21T13:52:20.627+0000",
     *     "status": 400,
     *     "error": "Bad Request",
     *     "message": "指定路径不允许访问",
     *     "path": "/log/novisit"
     * }
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getRequestURI().contains("/novisit")){
            response.sendError(400,"指定路径不允许访问");
            return false;
        }
        request.setAttribute("param","我是参数");
        System.out.println("开始处理请求"+this.format.format(new Date()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("请求处理完毕"+this.format.format(new Date()));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图处理完毕"+this.format.format(new Date()));
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("并发处理开始"+this.format.format(new Date()));

    }
}
